package com.eternal.base.utils;

/**
 * Created by Administrator
 * On 2019/9/4
 * Description:CRC校验
 * @author Administrator
 */
public class CRCUtil {
    public static byte[]crc16(byte[] bytes) {
        int crc = 0xFFFF;
        for (byte aByte : bytes) {
            crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
            // byte to int, trunc sign
            crc ^= (aByte & 0xff);
            crc ^= ((crc & 0xff) >> 4);
            crc ^= (crc << 12) & 0xffff;
            crc ^= ((crc & 0xFF) << 5) & 0xffff;
        }
        crc &= 0xffff;
        byte[] crcByte = new byte[2];
        crcByte[0] = (byte) ((crc >> 8) & 0xff);
        crcByte[1] = (byte) (crc & 0xff);
        return crcByte;
    }

    public static byte[] crc16(byte[] bytes, int index, int len){
        int crc=0xFFFF;
        for(int i=index; i<index+len; ++i){
            crc = ((crc >>> 8) | (crc << 8)) & 0xFFFF;
            crc ^= (bytes[i] & 0xFF);
            crc ^= ((crc & 0xFF) >> 4);
            crc ^= (crc << 12) & 0xFFFF;
            crc ^= ((crc & 0xFF) << 5) & 0xFFFF;
        }
        crc &= 0xFFFF;
        byte[] crcByte=new byte[2];
        crcByte[0]=(byte) ((crc >> 8) & 0xFF);
        crcByte[1]=(byte) (crc & 0xFF);
        return crcByte;
    }
}
